<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          :disabled="showEdit && menuName == '医院介绍'"
        />
      </el-form-item>
      <el-form-item label="封面图" prop="thumb">
        <div>
          <el-radio-group
            v-if="!formData.thumb"
            v-model="imageType"
            @change="handleImageTypeChange"
            :disabled="showEdit && menuName == '医院介绍'"
          >
            <el-radio :label="0">上传</el-radio>
            <el-radio :label="1">选择</el-radio>
          </el-radio-group>
          <UploadImg
            v-if="imageType == 0 || formData.thumb"
            v-model="formData.thumb"
            height="80px"
            :disabled="showEdit && menuName == '医院介绍'"
          />
        </div>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor v-if="showEditor" v-model="formData.content" height="350px" :readonly="showEdit && menuName == '医院介绍'" />
      </el-form-item>
      <el-form-item v-if="menuName == '医院介绍'">
        <el-button v-if="showEdit && formData.status != 10" type="primary" @click="showEdit = false"
          >修改</el-button
        >
        <el-button v-if="!showEdit && formData.status != 10" type="primary" @click="submitForm(0)"
          >保存</el-button
        >
        <el-button v-if="!showEdit && formData.status != 10" type="primary" @click="submitForm(1)"
          >提交审批</el-button
        >
      </el-form-item>
      <el-form-item v-else>
        <el-button type="primary" @click="submitForm(0)">保存</el-button>
      </el-form-item>
    </el-form>

    <ChooseImage ref="chooseImageRef" @choose="chooseImageChange" />
  </div>
</template>
<script setup lang="ts">
import { ContentTextApi, ContentTextVO } from '@/api/cms/contenttext'
import ChooseImage from './ChooseImage.vue'

/** 文本内容 表单 */
defineOptions({ name: 'ContentTextForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const imageType = ref(0)
const showEdit = ref(true)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogImageVisible = ref(false) // 弹窗的是否展示
const chooseImageRef = ref() // 表单 Ref
const showEditor = ref(true)
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  menuId: undefined,
  title: undefined,
  thumb: undefined,
  content: undefined,
  status: undefined
})
const formRules = reactive({
  menuId: [{ required: true, message: '菜单ID不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const menuName = ref('')

/** 打开弹窗 */
const open = async (menuId, name) => {
  menuName.value = name
  showEditor.value = false
  setTimeout(() => {
    showEditor.value = true
  }, 100)
  resetForm()
  // 修改时，设置数据
  if (menuId) {
    formLoading.value = true
    try {
      formData.value = (await ContentTextApi.getByMenuId(menuId)) || {}
      if (!formData.value.menuId) {
        formData.value.menuId = menuId
      }
    } finally {
      formLoading.value = false
    }
    showEdit.value = true
  } else {
    formData.value.menuId = menuId
    showEdit.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  if (type === 0) {
    try {
      const data = formData.value as unknown as ContentTextVO
      if (data.id) {
        await ContentTextApi.createContentText(data)
        message.success(t('common.updateSuccess'))
      } else {
        await ContentTextApi.createContentText(data)
        message.success(t('common.createSuccess'))
      }
      // showEdit.value = true

      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  } else {
    try {
      const data = formData.value as unknown as ContentTextVO
      if (data.id) {
        await ContentTextApi.createContentText(data)
      } else {
        await ContentTextApi.createContentText(data)
      }
      formData.value = (await ContentTextApi.getByMenuId(formData.value.menuId)) || {}
      ContentTextApi.submitContentText({ id: formData.value.id })
      message.success(t('common.createSuccess'))
      showEdit.value = true

      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }
}

const handleImageTypeChange = (val) => {
  imageType.value = val
  if (val == 1) {
    chooseImageRef.value.open(0)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    menuId: undefined,
    title: undefined,
    thumb: undefined,
    content: undefined,
    status: undefined
  }
  formRef.value?.resetFields()
}

const chooseImageChange = (data) => {
  formData.value.thumb = data
}
</script>